package services

import (
	"encoding/base64"
	"errors"
	"github.com/gin-gonic/gin"
	"http_server/src/common_util"
	"http_server/src/config"
	"http_server/src/models"
	"http_server/src/rpc_client"
	"http_server/src/utils"
)

type UserService interface {
	Login(c *gin.Context, req models.LoginRequest) (*models.LoginResponse, error)
	UpdateUserMessage(username string, nickname string, picture []byte) (*models.UpdateUserMessageResponse, error)
	GetUserMessage(username string) (*models.User, error)
}

type userService struct{}

func NewUserService() UserService {
	return &userService{}
}

// Login 登录认证接口
func (s *userService) Login(c *gin.Context, req models.LoginRequest) (*models.LoginResponse, error) {
	result, err := rpc_client.RPCCall(common_util.LoginMethod, req.Username, req.Password)
	if err != nil {
		return nil, err
	}
	rpcRes := transMapToStruct(result.(map[string]interface{}))
	var res models.LoginResponse
	switch rpcRes.Code {
	case 1:
		res.Message = config.HttpLoginSuccessMessage
		res.Code = config.HttpLoginSuccessCode
		res.Data = struct {
			Token string `json:"token"`
		}{Token: req.Username + ":" + rpcRes.Token}
	case 0:
		rpcRes.Code = config.HttpAuthFailCode
		rpcRes.Message = config.HttpLoginFailMessage
	default:
		return nil, errors.New("TCP Server 内部服务错误")
	}
	return &res, nil
}

func (s *userService) UpdateUserMessage(username string, nickname string, picture []byte) (*models.UpdateUserMessageResponse, error) {
	// 将图片数据编码为 base64 字符串
	pictureBase64 := base64.StdEncoding.EncodeToString(picture)
	result, err := rpc_client.RPCCall(common_util.UpdateUserMessageMethod, username, nickname, pictureBase64)
	if err != nil {
		return nil, err
	}
	resp := utils.TransInterfaceToInt(result)
	if resp != 1 {
		return nil, errors.New("调用TCP Server 进行用户个人信息的更改出现失败，请检查TCP Server服务日志")
	}
	return &models.UpdateUserMessageResponse{Code: 200, Message: "更新数据成功"}, nil
}

func (s *userService) GetUserMessage(username string) (*models.User, error) {
	result, err := rpc_client.RPCCall(common_util.GetUserMessageMethod, username)
	if err != nil {
		return nil, err
	}
	mapResult := result.(map[string]interface{})
	if code, ok := mapResult["code"]; !ok {
		if utils.TransInterfaceToInt(code) != 1 {
			common_util.InfoLogger.Println("从TCP Server 未能获取到该用户的基本个人信息， 用户username：" + username)
		}
	}
	return transMapToUserStruct(mapResult)
}

func transMapToUserStruct(data map[string]interface{}) (*models.User, error) {
	user := &models.User{}
	if nickname, ok := data["nickname"].(string); ok {
		user.Nickname = nickname
	}
	if username, ok := data["username"].(string); ok {
		user.Username = username
	}
	if pictureData, ok := data["picture"].(string); ok {
		user.Picture = pictureData
	}
	return user, nil
}

func transMapToStruct(data map[string]interface{}) *common_util.RPCLoginResponse {
	rpcRes := &common_util.RPCLoginResponse{}
	if val, ok := data["code"]; ok {
		rpcRes.Code = utils.TransInterfaceToInt(val)
	}
	if message, ok := data["message"].(string); ok {
		rpcRes.Message = message
	}
	if token, ok := data["token"].(string); ok {
		rpcRes.Token = token
	}
	return rpcRes
}
